package cn.ztuo.bitrade.controller;

import cn.ztuo.bitrade.constant.BooleanEnum;
import cn.ztuo.bitrade.constant.TransactionType;
import cn.ztuo.bitrade.core.DB;
import cn.ztuo.bitrade.core.DataException;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.entity.transform.AuthMember;
import cn.ztuo.bitrade.service.*;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import cn.ztuo.bitrade.util.Md5;
import cn.ztuo.bitrade.util.MessageResult;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static cn.ztuo.bitrade.constant.SysConstant.SESSION_MEMBER;


@RestController
@RequestMapping(value = "/ore")
@Slf4j
public class OreController extends BaseController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private CesspitService cesspitService;
    @Autowired
    private CesspitRecordService cesspitRecordService;
    @Autowired
    private CesspitAwardService awardService;
    @Autowired
    private MemberTransactionService transactionService;
    @Autowired
    private SysCfService sysCfService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private AwardService odfAwardServer;
    @Autowired
    private TeamService teamService;

    //币种精度保留
    private static final int DEFAULT_DIV_SCALE = 4;

    private static final String CARD="ODFc6HgWvT8VwBYDeJ12BkzFnGHLnYdau2Ep";
    /**
     * 获取矿机列表
     *
     * @return
     */
    @GetMapping("/oreList")
    public MessageResult orelist() {
        List<Cesspit> cesspits = cesspitService.findAll();
        if (cesspits.size() > 0) return success(cesspits);
        return success("ore null");
    }

    /**
     * 购买矿机
     *
     * @param authMember
     * @param id
     * @param jyPassword
     * @return
     */
    @PostMapping("/buyOre")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult MessageResult(
            @SessionAttribute(SESSION_MEMBER) AuthMember authMember,
            Long id,
            String jyPassword
    ) {
        try {
            String unit = null;
            if (jyPassword == null || jyPassword.equals("")) throw new Exception("安全密码不能为空");
            Boolean success = relationService.findActivation(authMember.getId());
            if (!success) throw new Exception("账号未激活");
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) throw new Exception("您当前账户已禁用，请联系客服！");
            //如果已经购买矿机不能购买只能升级
            ArrayList<Long> arrayList = new ArrayList<>();
            arrayList.add(1L);
            List<CesspitRecord> ores = cesspitRecordService.findByMemberIdAndStatusIn(authMember.getId(), arrayList);
            if (ores.size() > 0) throw new Exception("不能重复质押矿机，请升级矿机");
            //验证交易密码
            String mbPassword = member.getPassword();
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword)) return MessageResult.error(400, "安全密码错误");
            Cesspit ore = cesspitService.findById(id);
            unit = ore.getCoin().toUpperCase();
            if (ore.getStatus() != 1) throw new Exception("矿机未开启");
            //验证数量
            BigDecimal amount = new BigDecimal(ore.getMin());
            //获取算力
            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(ore.getCoin(), authMember.getId());
            if (!BigDecimalUtils.compare(memberWallet.getBalance(), amount)) throw new Exception("账户资产不足");
            int is_success = cesspitService.subAmount(amount, memberWallet, member.getId());
            //封装购买矿机记录
            if (is_success == 1) {
                CesspitRecord cess = new CesspitRecord();
                cess.setCesspitId(ore.getId());
                cess.setCoin(unit);
                cess.setCreateTime(new Date());
                cess.setDay(ore.getDay());
                cess.setEarning(ore.getProportion());
                cess.setImage(ore.getImage());
                cess.setMemberId(authMember.getId());
                cess.setUserName(member.getUsername());
                cess.setNumber(ore.getMin());
                cess.setHashrate(ore.getEarning());
                cess.setName(ore.getName());
                cess.setStatus(1L);
                CesspitRecord cesspitRecord = cesspitRecordService.save(cess);
                if (cesspitRecord.getId() > 0) {
                    // 交易记录
                    MemberTransaction transaction = new MemberTransaction();
                    transaction.setAmount(new BigDecimal(cess.getNumber()).negate());
                    transaction.setSymbol(cess.getCoin());
                    transaction.setAddress("");
                    transaction.setMemberId(cess.getMemberId());
                    transaction.setType(TransactionType.BUYCALCULATEFORCE);
                    transaction.setFee(BigDecimal.ZERO);
                    transaction.setCreateTime(new Date());
                    transaction.setRemark("矿机质押");

                    MemberWallet odfWallet2 = memberWalletService.findByCoinUnitAndMemberId(cess.getCoin(),cess.getMemberId());
                    transaction.setFromAddress(odfWallet2.getAddress());
                    transaction.setToAddress(CARD);
                    transaction.setStatus(5);


                    transactionService.save(transaction);
                } else {
                    throw new Exception("矿机质押失败");
                }
            } else {
                throw new Exception("矿机质押失败");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return MessageResult.error(400, e.getMessage());
        }
        return MessageResult.success("矿机质押成功");
    }

    @PostMapping("buylevelOre")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult buylevelOre(
            @SessionAttribute(SESSION_MEMBER) AuthMember authMember,
            @RequestParam(value = "jyPassword", required = true) String jyPassword,
            @RequestParam(value = "id", required = true) Long id) {
        try {
            if (jyPassword == null || jyPassword.equals("")) throw new Exception("安全密码不能为空");
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) throw new Exception("您当前账户已禁用，请联系客服！");
            String mbPassword = member.getPassword();
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                throw new Exception("安全密码错误");
            CesspitRecord cesspit = cesspitRecordService.findByMemberIdAndStatus(member.getId(), 1L);
            if (cesspit == null) throw new Exception("未找到质押矿机");
            Cesspit ore = cesspitService.findById(id);
            if (cesspit == null) throw new Exception("未找到升级矿机");
            if (cesspit.getStatus() == 2) throw new Exception("矿机未开启，请选择升级其他类型矿机");
            if (cesspit.getNumber() >= ore.getMin()) throw new Exception("升级矿机失败，只能选择更高等级的矿机");
            //获取升级矿机的差价
            Long money = ore.getMin() - cesspit.getNumber();
            Cesspit orenewdefine = cesspitService.findById(cesspit.getCesspitId());

            BigDecimal diff = BigDecimalUtils.sub(cesspit.getHashrate(),orenewdefine.getEarning());
            if(diff.compareTo(BigDecimal.ZERO) < 0)
            {
                diff = BigDecimal.ZERO;
            }

            BigDecimal amount = new BigDecimal(money);
            //获取算力
            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(ore.getCoin(), member.getId());
            if (!BigDecimalUtils.compare(memberWallet.getBalance(), amount)) throw new Exception("账户资产不足");
            int is_success = cesspitService.subAmount(amount, memberWallet, member.getId());
            if (is_success == 1) {
                CesspitRecord cess = new CesspitRecord();
                cess.setCesspitId(ore.getId());
                cess.setCoin(ore.getCoin());
                cess.setCreateTime(new Date());
                cess.setDay(ore.getDay());
                cess.setEarning(ore.getProportion());
                cess.setImage(ore.getImage());
                cess.setMemberId(authMember.getId());
                cess.setUserName(member.getUsername());
                cess.setNumber(ore.getMin());
                cess.setHashrate(ore.getEarning().add(diff));
                cess.setName(ore.getName());
                cess.setStatus(1L);
                CesspitRecord cesspitRecord = cesspitRecordService.save(cess);
                if (cesspitRecord.getId() > 0) {
                    //如果升级矿机成功，把之前矿机标记类型为4软删除
                    cesspit.setStatus(4L);
                    cesspitRecordService.save(cesspit);
                    // 交易记录添加交易记录
                    MemberTransaction transaction = new MemberTransaction();
                    transaction.setAmount(amount.negate());
                    transaction.setSymbol(cess.getCoin());
                    transaction.setAddress("");
                    transaction.setMemberId(cess.getMemberId());
                    transaction.setType(TransactionType.BUYCALCULATEFORCE);
                    transaction.setFee(BigDecimal.ZERO);
                    transaction.setCreateTime(new Date());
                    transaction.setRemark("矿机升级");
                    MemberWallet odfWallet2 = memberWalletService.findByCoinUnitAndMemberId(cess.getCoin(),cess.getMemberId());
                    transaction.setFromAddress(odfWallet2.getAddress());
                    transaction.setToAddress(CARD);
                    transaction.setStatus(6);
                    transactionService.save(transaction);
                } else {
                    throw new Exception("矿机升级失败");
                }
            } else {
                throw new Exception("矿机升级失败");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return error(400, e.getMessage());
        }
        return success("矿机升级成功");
    }

    /**
     * 获取可升级矿机列表
     *
     * @param authMember
     * @return
     */
    @PostMapping("levelOre")
    public MessageResult levelOre(@SessionAttribute(SESSION_MEMBER) AuthMember authMember) {
        //查询当前用户质押的矿机
        CesspitRecord ore = cesspitRecordService.findByMemberIdAndStatus(authMember.getId(), 1L);
        if (ore == null) return MessageResult.error(400, "无质押矿机");
        List<Cesspit> ores = cesspitService.selectGtMin(ore.getNumber());
        return success(ores);
    }


    /**
     * 赎回质押币种，固定天数平均返回
     *
     * @param authMember
     * @param id
     * @return
     */
    @PostMapping("redeem")
    public MessageResult redeem(
            @SessionAttribute(SESSION_MEMBER) AuthMember authMember,
            @RequestParam(value = "id", required = true) Long id,
            String jyPassword
    ) throws Exception {
        //验证交易密码
        if (jyPassword == null || jyPassword.equals("")) return error(400, "安全密码不能为空");
        Member member = memberService.findOne(authMember.getId());
        String mbPassword = member.getPassword();
        if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
            return MessageResult.error(400, "安全密码错误");
        CesspitRecord ore = cesspitRecordService.findById(id);
        if (ore == null) return error(400, "记录未找到");
        if (ore.getStatus() != 1) return error(400, "质押已结束或赎回");
        if(member.getLockRedeem() ==2) return error(400, "禁止赎回");


        ore.setStatus(3L);
        cesspitRecordService.save(ore);
        return MessageResult.success("赎回成功");
    }

    /**
     * 获取个人矿机列表
     *
     * @param authMember
     * @param pageNum
     * @param pageSize
     * @param coin
     * @return
     */
    @PostMapping("myOreList")
    public MessageResult myList(
            @SessionAttribute(SESSION_MEMBER) AuthMember authMember,
            @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "coin") String coin
    ) {
        Page<CesspitRecord> ores = cesspitRecordService.getPage(pageNum, pageSize, coin, authMember.getId());
        return MessageResult.getSuccessInstance("成功", ores);
    }

    /**
     * 矿机赎回
     * 按矿机的赎回天数，平均返回每日的质押币种
     */
    @Scheduled(cron = "0 1 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void AutoRedeem() {
        List<CesspitRecord> ores = cesspitRecordService.findAll();
        ores.stream().filter(ore -> ore.getStatus() == 3).forEach(ore -> {
            BigDecimal number = BigDecimalUtils.div(new BigDecimal(ore.getNumber()), new BigDecimal(ore.getDay()), DEFAULT_DIV_SCALE);
            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(ore.getCoin(), ore.getMemberId());
            memberWalletService.increaseBalance(memberWallet.getId(), number);
            MemberTransaction transaction = new MemberTransaction();
            transaction.setAmount(number);
            transaction.setSymbol(ore.getCoin());
            transaction.setAddress("");
            transaction.setMemberId(ore.getMemberId());
            transaction.setType(TransactionType.REDEMPTION);
            transaction.setFee(BigDecimal.ZERO);
            transaction.setCreateTime(new Date());
            transaction.setRemark("质押赎回");
            MemberWallet odfWallet2 = memberWalletService.findByCoinUnitAndMemberId(ore.getCoin(),ore.getMemberId());
            transaction.setFromAddress(CARD);
            transaction.setToAddress(odfWallet2.getAddress());
            transaction.setStatus(7);
            transactionService.save(transaction);
            Long day = ore.getNowDay() + 1;
            if (day >= ore.getDay()) {
                ore.setStatus(2L);
            }
            ore.setNowDay(day);
            cesspitRecordService.save(ore);
        });
    }

    /*
    @RequestMapping(value = "ReCompute", method = RequestMethod.GET)
    public String Recomputing()
    {
        return clearing();
    }*/

    /**
     * 质押矿机每日结算
     *
     * @return
     */
    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional
    public String clearing() {
        //结算的开关
        SysCf config = sysCfService.configOneCname("isopen");
        if (config.getValue().equals("2")) {
            log.info("结算质押矿机收益未开启");
            return "结算收益未开启";
        }
        log.info("开始结算");

        //获取ODF对USDT的价格
//        if(finalDfPrice.compareTo(BigDecimal.ZERO) <=0)
//        {
//            RestTemplate restTemplate = new RestTemplate();
//            String StringData = restTemplate.getForObject("https://sapi.odf.plus/market/symbol-thumb",String.class);
//            JSONArray data= JSONArray.fromObject(StringData);
//            finalDfPrice = new BigDecimal("1");
//            for(int i=0;i<data.size();i++){
//                net.sf.json.JSONObject json =  data.getJSONObject(i);
//                if(json.get("symbol").equals("ODF/USDT")){
//                    finalDfPrice = new BigDecimal(json.get("usdRate").toString());
//                    break;
//                }
//            }
//        }
        final BigDecimal  finalDfPrice = new BigDecimal(sysCfService.configOneCname("releaseprice").getValue());

        //获取当前所有用户的质押算力总和
        String[] getMax = cesspitRecordService.sumHashRate();
        BigDecimal max = new BigDecimal(getMax[0]);
        //遍历所有购买的矿机
        List<CesspitRecord> ores = cesspitRecordService.findAll();
        //获取所有用户的社区算力加权值总和
        BigDecimal userAllSum = relationService.allWeighted();

        ores.stream().filter(ore -> ore.getStatus() == 1).forEach(ore -> {
           // System.out.println(finalDfPrice);
            Cesspit cesspit = cesspitService.findById(ore.getCesspitId());
            //每日矿机产量获取
            SysCf rewardInfo = sysCfService.configOneCname("reward");
            //静态分配收益总数量
            BigDecimal reward1 = BigDecimalUtils.mul(new BigDecimal(rewardInfo.getValue()), 0.5);
            //动态分配收益总数量
            BigDecimal reward2 = BigDecimalUtils.sub(new BigDecimal(rewardInfo.getValue()), reward1);
            //个人静态收益总量获取 =  个人算力(hashrate)/全会员算力(max)*reward1
            //算力占比
            BigDecimal lv = BigDecimalUtils.div(ore.getHashrate(), max, DEFAULT_DIV_SCALE);
            //获取个人算力静态收益总和
            BigDecimal oneReward = BigDecimalUtils.mulDown(reward1, lv, DEFAULT_DIV_SCALE);
            //当前用户的社区算力加权值
            BigDecimal userSum = relationService.weighted(ore.getMemberId());
            BigDecimal odflv = BigDecimalUtils.sub(new BigDecimal("1"),cesspit.getProportion());
            if (userSum.compareTo(BigDecimal.ZERO) != 0) {
                //个人社区加权值占用比例
                BigDecimal twoReward = BigDecimalUtils.mulDown(BigDecimalUtils.div(userSum, userAllSum, 16), reward2, DEFAULT_DIV_SCALE);
                //剩余ODF数量
                MemberWallet wallet4= memberWalletService.findByCoinUnitAndMemberId("ODF", ore.getMemberId());

                BigDecimal usermax= BigDecimalUtils.mul(ore.getNumber(),0.25);
                if(twoReward.compareTo(usermax) > 0)
                    twoReward = usermax;
                memberWalletService.increaseBalance(wallet4.getId(), twoReward);
                //添加社区收益记录
                MemberTransaction transaction = new MemberTransaction();
                transaction.setAmount(twoReward);
                transaction.setSymbol(ore.getCoin());
                transaction.setAddress("");
                transaction.setMemberId(ore.getMemberId());
                transaction.setType(TransactionType.HASHRATES);
                transaction.setFee(BigDecimal.ZERO);
                transaction.setCreateTime(new Date());
                transaction.setRemark("社区算力收益");
                MemberWallet odfWallet2 = memberWalletService.findByCoinUnitAndMemberId(ore.getCoin(),ore.getMemberId());
                transaction.setFromAddress(CARD);
                transaction.setToAddress(odfWallet2.getAddress());
                transaction.setStatus(8);
                transactionService.save(transaction);
                //添加社区手续费记录
//                Award award = new Award();
//                award.setNumber(twoReward);
//                award.setCreateTime(new Date());
//                award.setStatus(1L);
//                award.setType(3L);
//                award.setUid(ore.getMemberId());
//                award.setUnit("ODF");
//                odfAwardServer.save(award);
            }
            //按比例分配收益给用户，添加静态收益记录
            //转换USDT数量
            BigDecimal odfAmount = BigDecimalUtils.mulRound(oneReward,cesspit.getProportion(),DEFAULT_DIV_SCALE);
            //把对应比例的ODF转为USDT
            BigDecimal oneReward1 = BigDecimalUtils.mulRound(odfAmount, finalDfPrice,DEFAULT_DIV_SCALE);
            MemberWallet wallet1 = memberWalletService.findByCoinUnitAndMemberId("USDT", ore.getMemberId());
            memberWalletService.increaseBalance(wallet1.getId(), oneReward1);

            //添加账单记录
            MemberTransaction transaction2 = new MemberTransaction();
            transaction2.setAmount(oneReward1);
            transaction2.setSymbol("USDT");
            transaction2.setAddress("");
            transaction2.setMemberId(ore.getMemberId());
            transaction2.setType(TransactionType.HASHRATE);
            transaction2.setFee(BigDecimal.ZERO);
            transaction2.setCreateTime(new Date());
            transaction2.setRemark("算力回购"+odfAmount+"ODF");
            MemberWallet odfWallet2 = memberWalletService.findByCoinUnitAndMemberId(ore.getCoin(),ore.getMemberId());
            transaction2.setFromAddress(CARD);
            transaction2.setToAddress(odfWallet2.getAddress());
            transaction2.setStatus(9);
            transactionService.save(transaction2);

            //剩余ODF数量
            BigDecimal oneReward2 = BigDecimalUtils.mulRound(oneReward,odflv,DEFAULT_DIV_SCALE);
            MemberWallet wallet2 = memberWalletService.findByCoinUnitAndMemberId("ODF", ore.getMemberId());
            memberWalletService.increaseBalance(wallet2.getId(), oneReward2);
            //添加账单记录
            MemberTransaction transaction = new MemberTransaction();
            transaction.setAmount(oneReward2);
            transaction.setSymbol(ore.getCoin());
            transaction.setAddress("");
            transaction.setMemberId(ore.getMemberId());
            transaction.setType(TransactionType.HASHRATE);
            transaction.setFee(BigDecimal.ZERO);
            transaction.setCreateTime(new Date());
            transaction.setRemark("质押算力收益");

            transaction.setFromAddress(CARD);
            transaction.setToAddress(odfWallet2.getAddress());
            transaction.setStatus(9);
            transactionService.save(transaction);
            //添加手续费记录
            Award award = new Award();
            award.setNumber(odfAmount);
            award.setCreateTime(new Date());
            award.setStatus(1L);
            award.setType(2L);
            award.setUid(ore.getMemberId());
            award.setUnit("ODF");
            odfAwardServer.save(award);
        });
        log.info("计算算力收益完成");
        return "计算算力收益完成";
    }

    /**
     * 获取算力和持币排名
     *
     * @param user
     * @param type
     * @return
     */
    @PostMapping("ranking")
    public MessageResult ranking(
            @SessionAttribute(SESSION_MEMBER) AuthMember user,
            @RequestParam(name = "type", required = true, defaultValue = "1") Long type) {
        ArrayList<Object> map = new ArrayList<>();
        HashMap<String, Object> queryMap = new HashMap<>();
        Long i = 1L;
        Long j = 0L;
        BigDecimal number = BigDecimal.ZERO;
        if (type == 1) {
            //算力排行
            List<CesspitRecord> cesss = cesspitRecordService.DongtaiAllHashrate();
            for (CesspitRecord cess : cesss) {
                JSONObject json = new JSONObject();
                json.put("username", "NO."+i);
                json.put("number", cess.getHashrate());
                json.put("id", i);
                if (cess.getMemberId() == user.getId()) j = i;
                map.add(JSONArray.fromObject(json));
                ++i;
                if (i > 100) break;
            }
            number = cesspitRecordService.getHashrate(user.getId());
        } else if (type == 2) {
            //持币排行
            List<MemberWallet> wallets = memberWalletService.findOrder("ODF");
            for (MemberWallet wallet : wallets) {
                try
                {
                    JSONObject json = new JSONObject();
                    json.put("number", wallet.getBalance());
                     json.put("username", wallet.getAddress()==null?"N/A":wallet.getAddress());
                    json.put("id", i);
                    if (wallet.getMemberId() == user.getId())
                        j = i;
                    map.add(JSONArray.fromObject(json));
                    ++i;
                }catch (Exception e)
                {
                    log.error(e.getMessage());
                }

                if (i > 100) break;
            }
            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId("ODF", user.getId());
            number = memberWallet.getBalance();
        } else {
            return error("获取排名错误");
        }
        //
        JSONObject other = new JSONObject();
        //个人排名信息
        JSONObject self = new JSONObject();
        self.put("username", user.getMobilePhone());
        self.put("number", number);
        self.put("ranking", j);
        other.put("selfRanking", self);
        //算力总和
        BigDecimal Max = BigDecimal.ZERO;
        if (type == 1) {
            String[] info1 = cesspitRecordService.sumHashRate();
            Max = new BigDecimal(info1[0]);
        } else {//持币总和
            String[] info2 = memberWalletService.sumBalance("ODF");
            Max = new BigDecimal(info2[0]);
        }
        JSONObject sumInfo = new JSONObject();
        sumInfo.put("username", "");
        sumInfo.put("number", Max);
        sumInfo.put("ranking", 0);
        other.put("sum", sumInfo);
        queryMap.put("one", JSONArray.fromObject(other));
        queryMap.put("ranking", map);
        return MessageResult.getSuccessInstance("成功", JSONArray.fromObject(queryMap));
    }

    /**
     * 排名奖励发放
     * @return
     */
    @Scheduled(cron = "0 10 3 * * ?")
    @Transactional
    public String rankDown(){
        //结算的开关
        SysCf config = sysCfService.configOneCname("rank");
        if (config.getValue().equals("2")) {
            log.info("排名结算未开启");
            return "排名结算未开启";
        }



        BigDecimal sum = odfAwardServer.sumAward("ODF");
        if(sum==null) return "无排名奖励";
        //获取空投的比例,根据比例获取空投的数量
        SysCf ranklvConfig = sysCfService.configOneCname("ranklv");
        BigDecimal ranklv = new BigDecimal(ranklvConfig.getValue());
        BigDecimal sumAward = BigDecimalUtils.mulRound(sum,ranklv,DEFAULT_DIV_SCALE);
        BigDecimal awards= BigDecimalUtils.div(sumAward,new BigDecimal("2"));
        log.info("今日排名空投数量"+awards);
        //获取排名收益信息
        List<Team> teams = teamService.findAll();
        //算力排行
        List<CesspitRecord> cesss = cesspitRecordService.DongtaiAllHashrate();
        int i = 0;
        for (CesspitRecord cess : cesss) {
            //当前用户名次
            ++i;
            //当前名次阶段有多少个人
            Long number = 0L;
            //当前用户排名收益
            BigDecimal oneAward = BigDecimal.ZERO;
            //获取加权值
            BigDecimal weighted = BigDecimal.ZERO;
            for (Team one:teams){
                if(i>=one.getTeams() && i<=one.getTeame()){
                    number = one.getTeame()-one.getTeams() +1;
                    weighted = new BigDecimal(one.getWeighted());
                    break;
                }
            }
            //计算用户的排名收益
            if(weighted.compareTo(BigDecimal.ZERO)>0) {
                oneAward = BigDecimalUtils.div(BigDecimalUtils.mulRound(awards, weighted, DEFAULT_DIV_SCALE), new BigDecimal(number));
                if(oneAward.compareTo(BigDecimal.ZERO)>0){
                    MemberWallet wallet3 = memberWalletService.findByCoinUnitAndMemberId("ODF", cess.getMemberId());
                    memberWalletService.increaseBalance(wallet3.getId(), oneAward);
                    //添加账单记录
                    MemberTransaction transaction = new MemberTransaction();
                    transaction.setAmount(oneAward);
                    transaction.setSymbol("ODF");
                    transaction.setAddress("");
                    transaction.setMemberId(cess.getMemberId());
                    transaction.setType(TransactionType.SAWARD);
                    transaction.setFee(BigDecimal.ZERO);
                    transaction.setCreateTime(new Date());
                    transaction.setRemark("算力排名奖励"+i+"名");
                    MemberWallet odfWallet2 = memberWalletService.findByCoinUnitAndMemberId("ODF",cess.getMemberId());
                    transaction.setFromAddress(CARD);
                    transaction.setToAddress(odfWallet2.getAddress());
                    transaction.setStatus(10);
                    transactionService.save(transaction);
                }
            }
        }
        log.info("算力排名奖励发放完成");
        List<MemberWallet> wallets = memberWalletService.findOrder("ODF");
        int k = 0;
        for (MemberWallet wallet : wallets) {
            ++k;
            Long number = 0L;
            //当前用户排名收益
            BigDecimal twoAward = BigDecimal.ZERO;
            //获取加权值
            BigDecimal weighted = BigDecimal.ZERO;
            for (Team one:teams){
                if(k>=one.getTeams() && k<=one.getTeame()){
                    number = one.getTeame()-one.getTeams() +1;
                    weighted = new BigDecimal(one.getWeighted());
                    break;
                }
            }
            if(weighted.compareTo(BigDecimal.ZERO)>0) {
                twoAward = BigDecimalUtils.div(BigDecimalUtils.mulRound(awards, weighted, DEFAULT_DIV_SCALE), new BigDecimal(number));
                if(twoAward.compareTo(BigDecimal.ZERO)>0){
                    MemberWallet walletTwo = memberWalletService.findByCoinUnitAndMemberId("ODF", wallet.getMemberId());
                    memberWalletService.increaseBalance(walletTwo.getId(), twoAward);
                    //添加账单记录
                    MemberTransaction transaction = new MemberTransaction();
                    transaction.setAmount(twoAward);
                    transaction.setSymbol("ODF");
                    transaction.setAddress("");
                    transaction.setMemberId(wallet.getMemberId());
                    transaction.setType(TransactionType.CAWARD);
                    transaction.setFee(BigDecimal.ZERO);
                    transaction.setCreateTime(new Date());
                    transaction.setRemark("持币排名奖励"+k+"名");

                    MemberWallet odfWallet2 = memberWalletService.findByCoinUnitAndMemberId("ODF",wallet.getMemberId());
                    transaction.setFromAddress(CARD);
                    transaction.setToAddress(odfWallet2.getAddress());
                    transaction.setStatus(11);
                    transactionService.save(transaction);
                }
            }
        }

        try {
            DB.query("update addresses set balance = balance + 91314 where address='ODF000000000000000000000000000000000'");

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (DataException e) {
            e.printStackTrace();
        }
        log.info("持币排名奖励发放完成");
        return "排名奖励发放完成";
    }
}
